package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.result.Result;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 导出运营数据报表
     *
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //获取过去30天
        LocalDate begin = LocalDate.now().plusDays(-30);
        LocalDate end = LocalDate.now().plusDays(-1);

        //调用根据时间段查询统计营业数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));

        //调用poi接口，获取模板对象
        try {
            XSSFWorkbook excel = new XSSFWorkbook(this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx"));
            //获取excel表的sheet页
            XSSFSheet sheet = excel.getSheet("Sheet1");
            //根据表格赋值
            sheet.getRow(1).getCell(1).setCellValue(begin + "至" + end);

            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            row = sheet.getRow(4);
            row.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //循环每一天
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                BusinessDataVO businessDataVO = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //根据表格为每一天的数据赋值
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO.getTurnover());
                row.getCell(3).setCellValue(businessDataVO.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO.getNewUsers());

            }
            //写过响应数据
            ServletOutputStream outputStream = response.getOutputStream();
            excel.write(outputStream);

            outputStream.flush();
            outputStream.close();
            excel.close();


        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 销量排名统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<SalesTop10ReportVO> top10(LocalDate begin, LocalDate end) {
        //1获取最小时间和最大时间
        LocalDateTime min = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime max = LocalDateTime.of(end, LocalTime.MAX);

        //2.调用mapper层根据最小最大时间查询菜品和销量
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.dishAndNumberByTime(min, max);

        //3.获取菜品集合与销量集合
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());

        //4.封装vo
        SalesTop10ReportVO salesTop10ReportVO = SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList, ","))
                .numberList(StringUtils.join(numberList, ","))
                .build();

        return Result.success(salesTop10ReportVO);
    }

    /**
     * 订单数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<OrderReportVO> orderStatistics(LocalDate begin, LocalDate end) {
        //1.获取每一天的时间,并封装
        ArrayList<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        //2.获取每一天的有效订单数量和总订单数量
        ArrayList<Integer> totalOrderList = new ArrayList();
        ArrayList<Integer> validOrderList = new ArrayList();
        for (LocalDate localDate : localDateList) {
            //2.1获取最小时间和最大时间
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);

            //2.2map封装最小大时间
            Map map = new HashMap();
            map.put("begin", min);
            map.put("end", max);
            //2.3调用Mapper层根据map查询总订单数量
            Integer totalOrderCount = orderMapper.getOrderCount(map);

            map.put("status", Orders.COMPLETED);
            //2.4调用Mapper层根据map查询有效订单数量
            Integer validOrderCount = orderMapper.getOrderCount(map);

            //2.5添加到集合
            totalOrderList.add(totalOrderCount);
            validOrderList.add(validOrderCount);

        }
        //3.获取有效订单总数量和总订单总数量
        Integer totalOrderCount = totalOrderList.stream().reduce(Integer::sum).get();
        Integer validOrderCount = validOrderList.stream().reduce(Integer::sum).get();

        //4.获取订单完成率
        Double orderCompletionRate = 0.0;
        if (totalOrderCount != 0) {
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }

        //5.封装vo
        OrderReportVO orderReportVO = OrderReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .orderCountList(StringUtils.join(totalOrderList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCountList(StringUtils.join(validOrderList, ","))
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
        return Result.success(orderReportVO);
    }

    /**
     * 用户数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<UserReportVO> userStatistics(LocalDate begin, LocalDate end) {
        //1.获取每一天的时间,并封装
        ArrayList<LocalDate> localDateList = new ArrayList<>();
        localDateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDateList.add(begin);
        }
        //2.获取每一天的新增用户和总用户
        ArrayList totalUserList = new ArrayList();
        ArrayList newUserList = new ArrayList();
        for (LocalDate localDate : localDateList) {
            //2.1获取最小时间和最大时间
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);

            //2.2map封装最小大时间
            Map map = new HashMap();
            map.put("begin", min);
            //2.3调用Mapper层根据map查询总用户
            Integer totalUserCount = userMapper.getUserCount(map);

            map.put("end", max);
            //2.4调用Mapper层根据map查询新增用户
            Integer newUserCount = userMapper.getUserCount(map);

            //2.5添加到集合
            totalUserList.add(totalUserCount);
            newUserList.add(newUserCount);

        }
        //3.封装到vo
        UserReportVO userReportVO = UserReportVO.builder()
                .dateList(StringUtils.join(localDateList, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();

        return Result.success(userReportVO);
    }

    /**
     * 营业额数据统计
     *
     * @param begin
     * @param end
     * @return
     */
    @Override
    public Result<TurnoverReportVO> turnoverStatistics(LocalDate begin, LocalDate end) {

        //1.获取每一天的时间，并封装
        ArrayList<LocalDate> dateList = new ArrayList<>();

        //1.1先添加初始时间
        dateList.add(begin);

        //1.2最后循环添加后一天
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        //2.获取每一天的营业额，并封装
        ArrayList<Double> turnoverList = new ArrayList<>();

        for (LocalDate localDate : dateList) {
            //2.1获取当天的最小时间
            LocalDateTime min = LocalDateTime.of(localDate, LocalTime.MIN);
            //2.2获取当天的最大时间
            LocalDateTime max = LocalDateTime.of(localDate, LocalTime.MAX);
            //2.3封装map，状态，最小，最大
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", min);
            map.put("end", max);
            //2.4调用Mapper层根据Map查询当天总营业额
            Double turnoverSum = orderMapper.sumByMap(map);
            //2.5营业额为null=0，不为null直接返回
            turnoverSum = turnoverSum == null ? 0 : turnoverSum;

            turnoverList.add(turnoverSum);

        }
        //3.封装vo
        TurnoverReportVO turnoverReportVO = TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();

        return Result.success(turnoverReportVO);
    }
}
